package com.carl.proxy;

import com.carl.config.Function;
import com.carl.config.MapperBean;
import com.carl.config.RealConfiguration;
import com.carl.session.RealSqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class RealMapperProxy implements InvocationHandler {

    private RealSqlSession sqlSession ;

    private RealConfiguration realConfiguration ;

    public RealMapperProxy(RealConfiguration realConfiguration, RealSqlSession sqlSession) {
        this.realConfiguration = realConfiguration;
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperBean readMapper = realConfiguration.readMapper("UserMapper.xml");
        if(method.getDeclaringClass().getName().equals(readMapper.getInterfaceName()) == false){
            return null;
        }
        List<Function> list = readMapper.getList();
        if(null != list || 0 != list.size()){
            for (Function function : list) {
                if(method.getName().equals(function.getFuncName())){
                    return sqlSession.selectOne(function.getSql(), String.valueOf(args[0]));
                }
            }
        }
        return null;
    }
}
